<?  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
 
class ConstructUsuario{
 
###############################################################################################     
############################################ TABLA ############################################
###############################################################################################
 
    public function viewTable($content){
            $CI =& get_instance();
            $CI->load->library('table');
            $CI->load->library('service');
            $CI->load->library('servicecore');
            $CI->load->library('doctrine');
            $CI->load->library('template');
            $CI->load->library('dbconfiguration');
            
            ##service adicionales###
            $CI->load->library('serviceusuario');
            
            ##Content##
            $modulesT=$CI->dbconfiguration->getModulesTabla();
            $content0=array('url'				=>$CI->service->getUrl(),
            				'urlWeb'			=>$CI->service->getUrl3(),
            				'name'				=>$content['CXModelo'],
            				'namePage'			=>$content['CXModeloSingular'],
            				'validacion'		=>"",
            				'javascript'		=>"",
            				'javascriptAlert'	=>true,
            				'btnAdd'			=>"<a href='".$CI->service->getUrl3().$content['CXRuta']."/add' class='btn btn-metis-3'>Agregar</a>",
            				'head'				=>$modulesT['usuario']);
                         
           $content=array_merge($content,$content0);
           
           
            ##Fin Content####
            
            ##UrlRows####
            $urlRows=array(	'view'		=>$CI->service->getUrl3().$content['CXRuta']."/view",
            				'edit'		=>$CI->service->getUrl3().$content['CXRuta']."/edit",
            				'delete'	=>$CI->service->getUrl3().$content['CXRuta']."/delete");
            ##Fin urlRows####
            
            ##Orden de las columnas de las tablas####
            
            $orden=array(	0	=>"num",
            				1	=>"apellidosnombres",
            				2	=>"dni",
            				3	=>"email",
            				4	=>"telefono",
            				5	=>"celular",
            				6	=>"rol");
            ##Fin Orden####
            
            ####Datos###
            $list=$CI->serviceusuario->lista();
            $propTabla=array(	'lista'			=>$list,
            					'orden'			=>$orden,
            					'url'			=>$urlRows,
            					'flagEdit'		=>1,
            					'flagDelete' 	=>0,
            					'flagView'		=>1,
            					'flagColorbox'	=>0,
            					'flagRestaurar'	=>0,
            					'flagOther'		=>0
            );
            ##Fin Datos####
            
           #####Contenedor###
            $propContenedor=array(	'botones'		=>'',
            						'tituloHtml'	=>'Lista de Usuarios',
            						'tamanho'		=>'',
            						'nameTabla'		=>'');
            
            ####Fin contenedor###
            
            
            $content['rows']=$CI->servicecore->arregloToString($propTabla);
            $CI->template->viewTable($propContenedor,$content);
            
             
            //return $content;
             
        }
         
##############################################################################################      
######################################### FORMULARIO #########################################
##############################################################################################
 
    public function form($content=NULL,$variable='Agregar',$id=0){
            $CI =& get_instance();
            $CI->load->library('form');
            $CI->load->library('service');
            $CI->load->library('doctrine');
            $CI->load->library('template');
            ###Librerias necesarias##
            $CI->load->library('serviceusuario');
            
            ##fin Liberias necesarias
         
            ####Inicializacion de Variables a usar####
            $value=NULL;
            $mode="";
            $ver="";
            $btnGuardar="";
            ### Fin de Inicuializacion de variables####
             
             
            ##Configuracion de Agregar, Editar y Ver####
            if($variable=='Agregar'){
                $mode=$mode=$CI->service->getUrl3().$content['CXRuta']."/add/submit";
                $btnGuardar='Guardar';
                
            }elseif($variable=='Editar' || $variable=='Ver'){
                if(isset($id)){
                     
                    if($variable=='Ver'){ 
                        $btnGuardar='Regresar';
                        $mode="javascript:history.back(-1);";
                        $ver='readonly';
                    }else{
                        $mode=$CI->service->getUrl3().$content['CXRuta']."/edit/".$id."/submit";
                        $btnGuardar='Modificar';
                        
                    }
                    //modificar
                    $values=$CI->service->encripArrayResult($CI->serviceusuario->data($id));
                    if(isset($values[0]))
                        $value=$values[0];
                    else
                        $value=NULL;
                }else
                $value=NULL;
            }
            ###Fin de Configuracion de Agregar, Editar y Ver#######
             
            ##Content##
            $content['url']=$CI->service->getUrl();
            $content['urlWeb']=$CI->service->getUrl3();
            $content["name"]="Formulario de ".$content['CXModeloSingular']." - ".$variable;
            $content['namePage']=$content['CXModeloSingular'];
            $content['btnAdd']='';
             
            ##Fin Content##
             
            ##Inicio Validaciones###
            $a=0;
            $validation[0]='required:true';
            $validation[1]='required:true';
            $validation[2]='required:true';
            $validation[3]='required:false';
            $validation[4]='required:false';
            $validation[5]='required:true';
            $validation[6]='required:true';
            $validation[7]='required:true';
            $validation[8]='required:true';
            $validation[9]='required:false';
            $validation[10]='required:true';
            $validation[11]='required:true';
            $validation[12]='required:true';
             
            ##Fin Validaciones##
         
            ###Llenar Select Necesarios para el formulario#####
            $perfiles=$CI->serviceperfil->returnPerfilSelectNoAsociados();
           
            ## Fin LLenar select necesarios para el formulario####
			
			$formForm=array('form'=>	array(	'id'		=>'block-validate',
												'class'		=>'form-horizontal',
												'action'	=>$mode,
												'method'	=>'post')
														);
			
			$formData=array('idrol'=>			array(	'type'		=>'select',
														'id'		=>'rol',
														'value'		=>$value['rol'],
														'readonly'	=>$ver,
														'selectValues'	=>$roles,
														'validation'	=>$validation[$a++]),
														
							'nombres'=>			array(	'type'		=>'text',
														'id'		=>'nombres',
														'value'		=>$value['nombres'],
														'readonly'	=>$ver,
														'validation'	=>$validation[$a++]),
														
							'apellidos'=>		array(	'type'		=>'text',
														'id'		=>'apellidos',
														'value'		=>$value['apellidos'],
														'readonly'	=>$ver,
														'validation'	=>$validation[$a++]),
														
							'dni'=>				array(	'type'		=>'text',
														'id'		=>'dni',
														'value'		=>$value['dni'],
														'readonly'	=>$ver,
														'validation'	=>$validation[$a++]),
														
							'fechanacimiento'=>	array(	'type'		=>'text',
														'id'		=>'fechanacimiento',
														'value'		=>$value['fechanacimiento'],
														'readonly'	=>$ver,
														'validation'	=>$validation[$a++]),
														
							'email'=>			array(	'type'		=>'text',
														'id'		=>'email',
														'value'		=>$value['email'],
														'readonly'	=>$ver,
														'validation'	=>$validation[$a++]),
														
							'telefono'=>		array(	'type'		=>'text',
														'id'		=>'telefono',
														'value'		=>$value['telefono'],
														'readonly'	=>$ver,
														'validation'	=>$validation[$a++]),							
														
							'celular'=>			array(	'type'		=>'text',
														'id'		=>'celular',
														'value'		=>$value['celular'],
														'readonly'	=>$ver,
														'validation'	=>$validation[$a++]),
								);
			
			$formSubmit=array($btnGuardar=>		array(	'type'		=>'submit',
														'value'		=>$btnGuardar,
														'class'		=>'btn btn-primary'),
														
							'regresar'=>		array(	'type'		=>'button',
														'value'		=>'Regresar',
														'class'		=>'btn btn-primary',
														'onclick'	=>'javascript:history.back(-1);')
														);
			
			
			$formHidden=array($content['CXModelo']=>	array(	'type'		=>'hidden',
																'id'		=>$content['CXModelo'],
																'value'		=>$value['id'])
														);
														
			$form= new $CI->form(12);
			$form->constructForm($mode,$formForm,$formData,$formSubmit,$formHidden);
			
			/*
         
            $form = new $CI->form(12);
            $form->createForm("id:block-validate,class:form-horizontal,action:".$mode.",method:post");
            
            $form->addSelectDefault('select','Rol','id:rol'.$ver,$validation[$a++],$roles,$value['rol']);
            $form->addCampoDefault('text','Nombres','id:nombres,value:'.$value['nombres'].$ver,$validation[$a++]);
            $form->addCampoDefault('text','Apellidos','id:apellidos,value:'.$value['apellidos'].$ver,$validation[$a++]);
            $form->addCampoDefault('text','DNI','id:dni,value:'.$value['dni'].$ver,$validation[$a++]);
			$form->addCampoDefault('date','Fecha de nacimiento','id:fechanacimiento,value:'.$value['fechanacimiento'].$ver,$validation[$a++]);
            $form->addCampoDefault('email','Email','id:email,value:'.$value['email'].$ver,$validation[$a++]);
            $form->addCampoDefault('text','Tel&eacute;fono','id:telefono,value:'.$value['telefono'].$ver,$validation[$a++]);
			$form->addCampoDefault('text','Celular','id:celular,value:'.$value['celular'].$ver,$validation[$a++]);
             
            if($variable=='Ver'){ 
            $form->addSubmit('type:button,value:Regresar,class:btn btn-primary,onClick:javascript:history.back(-1);'.$ver);
                        }else{
                        $btnArray[0]='type:submit,value:'.$btnGuardar.',class:btn btn-primary'.$ver;
                        $btnArray[1]='type:button,value:Regresar,class:btn btn-primary,onClick:javascript:history.back(-1);'.$ver;
                        $form->addSubmitVarios($btnArray);
             }
             
            ####Esto es para Editar######
            if($variable=='Editar' || $variable=='Ver'){
                $hidden[0]='id:'.$content['CXModelo'].',value:'.$value['id'];
                $form->addHidden($hidden);
            }
            ###Fin para Editar##########
			
			*/
             
             
            $content['contenido']=$form->returnForm($content['name']);
            $content["validacion"]=$form->returnValidacion();
            if($variable=='Ver')
            $content["javascript"]='<script>$("#rol").attr("disabled", true).trigger("liszt:updated");</script>';
            else
            $content["javascript"]='';
            $CI->template->viewForm($content); 
        }
 
##############################################################################################      
########################################### SUBMIT ###########################################
##############################################################################################
 
     
    public function submit($content,$id=0){
        $CI =& get_instance();
        $CI->load->library('service');
        $CI->load->library('doctrine');
        $CI->load->library('input');
        $em=$CI->doctrine->em;
        $em->getConnection()->beginTransaction();
         
        $class=$CI->service->declarateClass('Usuario');   
        $class2=$CI->service->declarateClass('Rol');

 
        try{
            
                if($content['CXModo']=='edit' || $content['CXModo']=='delete'){
                    $class = $em->getRepository('Entity\User')->find($id);
                    $class2 = $em->getRepository('Entity\Persona')->find($class->getIdpersona());
                     
                }
                if($content['CXModo']=='edit' || $content['CXModo']=='add'){
                    $class2->setNombres($CI->input->post('nombres'));
                    $class2->setApellidos($CI->input->post('apellidos'));
                    ###Ciudad
                    $class4 = $em->getRepository('Entity\Distrito')->find(intval($CI->input->post('distrito')));
                    $class2->setIddistrito($class4->getIddistrito());
                    #############
                    ###Nacionalidad
                    $class5 = $em->getRepository('Entity\Nacionalidad')->find(intval($CI->input->post('nacionalidad')));
                    $class2->setIdnacionalidad($class5->getIdnacionalidad());
                    #############
                    $class2->setTelefono($CI->input->post('telefono'));
                    $class2->setEmail($CI->input->post('email'));
                    $class2->setDni($CI->input->post('dni'));
                    $class2->setEliminado(0);
                    $em->persist($class2);
                    $em->flush();
                     
                    $class->setIdpersona($class2->getIdpersona());
                    ###Perfil
                    $class3 = $em->getRepository('Entity\Perfil')->find(intval($CI->input->post('perfil')));
                    if($content['CXModo']=='add')
                    $class->setIdperfil($class3->getIdperfil());
                     
                    ###User
                    if($CI->input->post('password')!='')
                    $class->setPassword(md5($CI->input->post('password')));
                    if($content['CXModo']=='add'){
                    $class->setTipo($CI->input->post('perfil'));
                    $class->setUsuario($CI->input->post('usuario'));
                    }
                    $class->setLugar($CI->input->post('lugar'));
                    //$class->setCodigousuario($CI->input->post('codigousuario'));  
                    $class->setEstado($CI->input->post('estado'));
                    $class->setEliminado(0);
                 
                }
                if($content['CXModo']=='delete'){
                    $class->setEliminado(1);
                    $class2->setEliminado(1);
                    //se debe eliminar de las demas tablas, eso aun esta x verse
                }
                 
                $em->persist($class);
                $em->flush();
                 
                $em->getConnection()->commit();
        }catch(Exception $e){
            $em->getConnection()->rollback();
            $em->close();
            throw $e;
             
            }
                header("location:".$CI->service->getUrl3().$content['CXRuta']);
                break;
         
         
        }
     
     
     
     
     
     
}
?>